using System;
using System.Threading;
using System.Threading.Tasks;
using RTMP.SimpleClient;
using RTMP.SimpleClient.Messages;
using RTMP.SimpleClient.Callbacks;

namespace RTMP.SimpleClient.Examples
{
    /// <summary>
    /// 综合示例：展示所有控制方法的回调形式用法
    /// </summary>
    public class ComprehensiveCallbackExample
    {
        public static async Task RunExample()
        {
            Console.WriteLine("=== 综合回调功能示例 ===");

            var client = new RTMPSimpleClient();

            try
            {
                // 连接到RTMP服务器
                await client.ConnectAsync("rtmp://182.254.168.213:1935/live");
                Console.WriteLine("已连接到RTMP服务器");

                // 演示完整的播放流程
                await DemonstratePlayWorkflow(client);

                await Task.Delay(2000);

                // 演示完整的发布流程
                await DemonstratePublishWorkflow(client);

                await Task.Delay(3000);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"示例执行时发生错误: {ex.Message}");
            }
            finally
            {
                try
                {
                    await client.CloseAsync();
                    Console.WriteLine("\n已断开RTMP连接");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"关闭连接时发生错误: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 演示完整的播放工作流程
        /// </summary>
        private static async Task DemonstratePlayWorkflow(RTMPSimpleClient client)
        {
            Console.WriteLine("\n=== 播放工作流程 ===");

            var workflowCompleted = new TaskCompletionSource<bool>();

            // 第一步：创建流
            await client.CreateStreamAsync(
                onSuccess: async streamId =>
                {
                    Console.WriteLine($"✅ 步骤1: 成功创建播放流, StreamID = {streamId}");

                    // 第二步：开始播放
                    await client.PlayAsync(
                        streamId: streamId,
                        streamName: "test_video",
                        onSuccess: () =>
                        {
                            Console.WriteLine("✅ 步骤2: 播放命令发送成功");
                        },
                        onStatus: status =>
                        {
                            Console.WriteLine($"📊 播放状态更新: {status.Code} - {status.Description}");
                            
                            // 根据不同状态处理
                            switch (status.Code)
                            {
                                case "NetStream.Play.Start":
                                    Console.WriteLine("🎬 播放开始");
                                    break;
                                case "NetStream.Play.StreamNotFound":
                                    Console.WriteLine("❌ 流未找到");
                                    workflowCompleted.TrySetResult(false);
                                    break;
                                case "NetStream.Play.Complete":
                                    Console.WriteLine("✅ 播放完成");
                                    workflowCompleted.TrySetResult(true);
                                    break;
                                default:
                                    Console.WriteLine($"ℹ️ 其他状态: {status.Code}");
                                    break;
                            }
                        },
                        onError: error =>
                        {
                            Console.WriteLine($"❌ 播放失败: {error}");
                            workflowCompleted.TrySetResult(false);
                        }
                    );
                },
                onError: error =>
                {
                    Console.WriteLine($"❌ 创建播放流失败: {error}");
                    workflowCompleted.TrySetResult(false);
                }
            );

            // 等待工作流程完成或超时
            var timeoutTask = Task.Delay(10000); // 10秒超时
            var completedTask = await Task.WhenAny(workflowCompleted.Task, timeoutTask);
            
            if (completedTask == timeoutTask)
            {
                Console.WriteLine("⏰ 播放工作流程超时");
            }
            else
            {
                var success = await workflowCompleted.Task;
                Console.WriteLine(success ? "🎉 播放工作流程完成" : "😞 播放工作流程失败");
            }
        }

        /// <summary>
        /// 演示完整的发布工作流程
        /// </summary>
        private static async Task DemonstratePublishWorkflow(RTMPSimpleClient client)
        {
            Console.WriteLine("\n=== 发布工作流程 ===");

            var workflowCompleted = new TaskCompletionSource<bool>();
            var statusUpdateCount = 0;

            // 第一步：创建流
            await client.CreateStreamAsync(
                onSuccess: async streamId =>
                {
                    Console.WriteLine($"✅ 步骤1: 成功创建发布流, StreamID = {streamId}");

                    // 第二步：开始发布
                    await client.PublishAsync(
                        streamId: streamId,
                        streamName: "test_publish",
                        publishType: "live",
                        onSuccess: () =>
                        {
                            Console.WriteLine("✅ 步骤2: 发布命令发送成功");
                        },
                        onStatus: status =>
                        {
                            statusUpdateCount++;
                            Console.WriteLine($"📊 发布状态更新 #{statusUpdateCount}: {status.Code} - {status.Description}");
                            
                            // 根据不同状态处理
                            switch (status.Code)
                            {
                                case "NetStream.Publish.Start":
                                    Console.WriteLine("📡 开始发布");
                                    break;
                                case "NetStream.Publish.BadName":
                                    Console.WriteLine("❌ 流名称无效");
                                    workflowCompleted.TrySetResult(false);
                                    break;
                                case "NetStream.Publish.Idle":
                                    Console.WriteLine("⏸️ 发布空闲");
                                    break;
                                default:
                                    Console.WriteLine($"ℹ️ 其他状态: {status.Code}");
                                    break;
                            }

                            // 收到几个状态更新后模拟完成
                            if (statusUpdateCount >= 3)
                            {
                                Console.WriteLine("✅ 收到足够的状态更新，模拟发布完成");
                                workflowCompleted.TrySetResult(true);
                            }
                        },
                        onError: error =>
                        {
                            Console.WriteLine($"❌ 发布失败: {error}");
                            workflowCompleted.TrySetResult(false);
                        }
                    );
                },
                onError: error =>
                {
                    Console.WriteLine($"❌ 创建发布流失败: {error}");
                    workflowCompleted.TrySetResult(false);
                }
            );

            // 等待工作流程完成或超时
            var timeoutTask = Task.Delay(15000); // 15秒超时
            var completedTask = await Task.WhenAny(workflowCompleted.Task, timeoutTask);
            
            if (completedTask == timeoutTask)
            {
                Console.WriteLine("⏰ 发布工作流程超时");
            }
            else
            {
                var success = await workflowCompleted.Task;
                Console.WriteLine(success ? "🎉 发布工作流程完成" : "😞 发布工作流程失败");
            }
        }
    }

    /// <summary>
    /// 高级用法示例：多流并发操作
    /// </summary>
    public class MultiStreamExample
    {
        public static async Task RunMultiStreamExample()
        {
            Console.WriteLine("=== 多流并发操作示例 ===");

            var client = new RTMPSimpleClient();

            try
            {
                await client.ConnectAsync("rtmp://182.254.168.213:1935/live");
                Console.WriteLine("已连接到RTMP服务器");

                // 同时创建多个流用于不同目的
                await CreateMultipleStreams(client);

                await Task.Delay(5000);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"多流示例执行时发生错误: {ex.Message}");
            }
            finally
            {
                try
                {
                    await client.CloseAsync();
                    Console.WriteLine("\n已断开RTMP连接");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"关闭连接时发生错误: {ex.Message}");
                }
            }
        }

        private static async Task CreateMultipleStreams(RTMPSimpleClient client)
        {
            var completedOperations = 0;
            var totalOperations = 4;
            var allCompleted = new TaskCompletionSource<bool>();

            void CheckCompletion()
            {
                Interlocked.Increment(ref completedOperations);
                if (completedOperations >= totalOperations)
                {
                    allCompleted.TrySetResult(true);
                }
            }

            // 流1：播放视频流
            await client.CreateStreamAsync(
                onSuccess: async streamId =>
                {
                    Console.WriteLine($"📺 创建视频播放流: StreamID = {streamId}");
                    await client.PlayAsync(streamId, "video_stream",
                        onSuccess: () => Console.WriteLine("📺 视频播放开始"),
                        onStatus: status => Console.WriteLine($"📺 视频状态: {status.Code}"),
                        onError: error => Console.WriteLine($"📺 视频错误: {error}")
                    );
                    CheckCompletion();
                },
                onError: error =>
                {
                    Console.WriteLine($"📺 创建视频流失败: {error}");
                    CheckCompletion();
                }
            );

            // 流2：播放音频流
            await client.CreateStreamAsync(
                onSuccess: async streamId =>
                {
                    Console.WriteLine($"🎵 创建音频播放流: StreamID = {streamId}");
                    await client.PlayAsync(streamId, "audio_stream",
                        onSuccess: () => Console.WriteLine("🎵 音频播放开始"),
                        onStatus: status => Console.WriteLine($"🎵 音频状态: {status.Code}"),
                        onError: error => Console.WriteLine($"🎵 音频错误: {error}")
                    );
                    CheckCompletion();
                },
                onError: error =>
                {
                    Console.WriteLine($"🎵 创建音频流失败: {error}");
                    CheckCompletion();
                }
            );

            // 流3：发布直播流
            await client.CreateStreamAsync(
                onSuccess: async streamId =>
                {
                    Console.WriteLine($"📡 创建直播发布流: StreamID = {streamId}");
                    await client.PublishAsync(streamId, "live_broadcast", "live",
                        onSuccess: () => Console.WriteLine("📡 直播发布开始"),
                        onStatus: status => Console.WriteLine($"📡 直播状态: {status.Code}"),
                        onError: error => Console.WriteLine($"📡 直播错误: {error}")
                    );
                    CheckCompletion();
                },
                onError: error =>
                {
                    Console.WriteLine($"📡 创建直播流失败: {error}");
                    CheckCompletion();
                }
            );

            // 流4：录制流
            await client.CreateStreamAsync(
                onSuccess: async streamId =>
                {
                    Console.WriteLine($"📹 创建录制发布流: StreamID = {streamId}");
                    await client.PublishAsync(streamId, "recorded_content", "record",
                        onSuccess: () => Console.WriteLine("📹 录制发布开始"),
                        onStatus: status => Console.WriteLine($"📹 录制状态: {status.Code}"),
                        onError: error => Console.WriteLine($"📹 录制错误: {error}")
                    );
                    CheckCompletion();
                },
                onError: error =>
                {
                    Console.WriteLine($"📹 创建录制流失败: {error}");
                    CheckCompletion();
                }
            );

            // 等待所有操作完成
            var timeoutTask = Task.Delay(10000);
            var completedTask = await Task.WhenAny(allCompleted.Task, timeoutTask);

            if (completedTask == timeoutTask)
            {
                Console.WriteLine("⏰ 多流操作超时");
            }
            else
            {
                Console.WriteLine("🎉 所有流操作完成");
            }
        }
    }
}